import React from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';

import ECharts from '@kuiper-components/echarts';
import s from './Counts.module.css';
import { number } from '../../../../../../common/formatter';
export default function Counts({ className, title, total, data }) {
	const { fields, chartOption } = React.useMemo(() => {
		const fields = [];
		for (let idx = 0; idx < data.length; idx++) {
			const { label, count, color } = data[idx];
			fields.push({
				key: label,
				cols: [
					// eslint-disable-next-line react/jsx-key
					<span className={s.color} style={{ background: color }} />,
					<span key={`${label}-label`} className={s.label}>
						{label}
					</span>,
					<span
						key={`${label}-count`}
						className={cn(s.count, idx !== 0 ? (idx !== 2 ? s.wd1 : s.wd2) : s.wd)}
					>
						{number(count)}
					</span>,
				],
			});
		}

		const chartOption = {
			grid: {
				top: 0,
				right: 0,
				bottom: 0,
				left: 0,
			},
			tooltip: {
				confine: true,
				trigger: 'item',
				formatter: '{b}告警次数: {c} ({d}%)',
			},
			series: {
				type: 'pie',
				radius: ['65%', '80%'],
				center: ['50%', '50%'],
				label: {
					normal: {
						show: false,
						position: 'outside',
					},
					emphasis: {
						show: false,
						textStyle: {
							fontSize: '20',
							fontWeight: 'normal',
						},
					},
				},
				labelLine: {
					normal: {
						show: false,
					},
					emphasis: {
						show: false,
					},
				},
				data: data.map(({ label: name, count: value, color }) => ({
					name,
					value,
					itemStyle: { color },
				})),
			},
		};

		return { fields, chartOption };
	}, [title, total, data]);

	return (
		<div className={cn(className, s.counts)}>
			<div className={s.chartBox}>
				<div className={cn(s.chartTxt, s.df)}>
					<p className={s.fs16}>{title}</p>
					<p className={s.chartBig}>{number(total)}</p>
				</div>
			</div>
			<div className={cn(s.charts)}>
				<div className={cn(s.f1)}>
					<ECharts className={s.chart} option={chartOption} />
				</div>
				<div className={cn(s.f1, s.ml1rem)}>
					{fields.map(({ key, cols }) => (
						<div key={key} className={s.item}>
							{cols}
						</div>
					))}
				</div>
			</div>
		</div>
	);
}

Counts.propTypes = {
	className: PropTypes.string,
	title: PropTypes.string.isRequired,
	total: PropTypes.number.isRequired,
	data: PropTypes.arrayOf(
		PropTypes.shape({
			color: PropTypes.string.isRequired,
			label: PropTypes.string.isRequired,
			count: PropTypes.number.isRequired,
		})
	).isRequired,
};

Counts.defaultProps = {
	className: s.counts,
};
